package com.wsgxj.controller.sys;

import com.wsgxj.constant.SysConstant;
import com.wsgxj.domain.sys.SysRole;
import com.wsgxj.domain.sys.SysUser;
import com.wsgxj.service.sys.SysRoleService;
import com.wsgxj.service.sys.SysUserService;
import com.wsgxj.util.ShiroUtil;
import com.wsgxj.vo.DataGridResult;
import com.wsgxj.vo.Query;
import com.wsgxj.vo.R;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/user")
public class SysUserController {

	@Autowired
	private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
	
	@RequestMapping("/{page}")
	public String listPage(@PathVariable String page, HttpServletRequest request) {
		//新增时初始化角色列表
        List<SysRole> roleList = sysRoleService.findAll();
        request.setAttribute("roleList", roleList);
	    return "sys/user/" + page;
	}

	//用户列表
	@RequestMapping("/list")
	@ResponseBody
	@RequiresPermissions({"sys:user:list"})
	public DataGridResult list(@RequestParam Map<String, Object> params) {
		
		//只有超级管理员，才能查看所有管理员列表
        if(ShiroUtil.getUserId() != SysConstant.ADMIN_ID) { params.put("createUserId", ShiroUtil.getUserId()); }
		
		//查询数据列表
		Query query = new Query(params);
		DataGridResult dgr = sysUserService.getPageList(query);
		return dgr;
	}

	//用户新增
    @RequestMapping("/add")
    @ResponseBody
    @RequiresPermissions({"sys:user:add"})
    public R add(@RequestBody SysUser user) {
        sysUserService.save(user);
        return R.ok();
    }

    //用户修改查询数据
    @RequestMapping("/info/{userId}")
    @ResponseBody
    @RequiresPermissions({"sys:user:info"})
    public R info(@PathVariable Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        return R.ok().put("user", sysUser);
    }

    //用户修改保存
    @RequestMapping("/update")
    @ResponseBody
    @RequiresPermissions({"sys:user:update"})
    public R update(@RequestBody SysUser user) {
        sysUserService.update(user);
        return R.ok();
    }

    @RequestMapping("/view")
    @ResponseBody
    @RequiresPermissions({"sys:user:view"})
    public R view(@RequestBody SysUser sysUser) {
        sysUserService.update(sysUser);
        return R.ok();
    }

    //用户删除
	@RequestMapping("/delete")
	@ResponseBody
	@RequiresPermissions({"sys:user:delete"})
	public R deleteMore(@RequestBody Long[] ids) {

	    //系统管理员不能删除
		if(ArrayUtils.contains(ids, SysConstant.ADMIN_ID)) {
			return R.error("系统管理员不能删除");
		}

		//当前用户不能删除
        if(ArrayUtils.contains(ids, ShiroUtil.getUserId())) { return R.error("当前用户不能删除"); }
		
		sysUserService.deleteBatch(ids);
		return R.ok();
	}
}

